package com.itheima.grow.util;

import org.apache.commons.lang3.StringUtils;

import java.security.SecureRandom;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 *
 * @author ChenYaWei
 * @date 2017年07月20日 下午8:12
 */
public class StringUtil {


    /**
    * @Description: 字符串0-10
    * @Param:
    * @return:
    * @Author: Join
    * @Date: 2022/11/21 13:46
    */
    public static final String NUMBER_CHAR = "0123456789";


    /**
     * 字符串0
     */
    public static final String ZERO = "0";

    /**
     * 空字符串
     */
    public static final String EMPTY = "";

    /**
     * 正则匹配
     *
     * @param regex
     * @param target
     * @return
     */
    public static boolean isMatch(String regex, String target) {
        if (StringUtils.isBlank(target)) {
            return false;
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher isMatch = pattern.matcher(target);
        return isMatch.matches();
    }


    /**
     * @Description: 流水号的生成
     * YYYYMMDDHHmmssSSS(18)+5位随机数如：
     * 2020 0109 163545 256 00001
     * @Param: [str]
     * @return: java.lang.String
     * @Author: Join
     * @Date: 2022/10/25 20:16
     */
    public static final String generatorSequenceNo(int length) {
        StringBuffer sb = new StringBuffer();
        Random random = new SecureRandom();
        for (int i = 0; i < length; i++) {
            sb.append(NUMBER_CHAR.charAt(random.nextInt(NUMBER_CHAR.length())));
        }
        return DateUtil.formatCurrentDate(DateUtil.FORMAT_16) + sb;
    }

    /**
     * 流水号生成
     * @param length
     * @return
     */
    public static final String generatorSequenceNoNew(int length) {
        StringBuffer sb = new StringBuffer();
        Random random = new SecureRandom();
        for (int i = 0; i < length; i++) {
            sb.append(NUMBER_CHAR.charAt(random.nextInt(NUMBER_CHAR.length())));
        }
        return DateUtil.formatCurrentDate(DateUtil.FORMAT_27) + sb;
    }

    /**
     * 判断字符串是否是json
     * @param str
     * @return
     */
    public static boolean getJSONType(String str) {
        boolean result = false;
        if (StringUtils.isNotBlank(str)) {
            str = str.trim();
            if (str.startsWith("{") && str.endsWith("}")) {
                result = true;
            } else if (str.startsWith("[") && str.endsWith("]")) {
                result = false;
            }
        }
        return result;
    }

}
